package vn.vfriends.soffice.facade;

import java.util.List;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import vn.vfriends.soffice.entity.Menu;
import vn.vfriends.soffice.entity.Permission;
import vn.vfriends.soffice.entity.User;

/**
 *
 * @author chaungoctuan@gmail.com
 */
@Stateless
@LocalBean
public class UserFacade extends AbstractFacade<User> {

    @PersistenceContext(unitName = "sOfficePU")
    private EntityManager em;

    public UserFacade() {
        super(User.class);
    }
    
    @Override
    protected EntityManager getEntityManager() {
        return em;
    }
    
    public User findByUsername(String username){
        Query query = em.createNamedQuery("User.findByUsername", User.class);
        query.setParameter("username", username);
        List<User> userList = query.getResultList();
        if(userList != null && !userList.isEmpty())
            return userList.get(0);
        else
            return null;
    }

    public List<String> findURLsOfUser(User user) {
        List<String> results;
        String jpql = "SELECT m.url FROM User u "
                    + "LEFT JOIN u.groups g "
                    + "LEFT JOIN g.menus m WHERE u.id = :id ";
        Query query = em.createQuery(jpql).setParameter("id", user.getId());
        results = query.getResultList();
        
        jpql = "SELECT p.url FROM User u "
                + "LEFT JOIN u.groups g "
                + "LEFT JOIN g.permissions p WHERE u.id = :id ";
        query = em.createQuery(jpql).setParameter("id", user.getId());
        results.addAll(query.getResultList());
        return results;
    }

    public List<Menu.Code> findMenusOfUser(User user) {
        String jpql = "SELECT m.code FROM User u "
                    + "LEFT JOIN u.groups g "
                    + "LEFT JOIN g.menus m WHERE u.id = :id ";
        Query query = em.createQuery(jpql).setParameter("id", user.getId());
        return query.getResultList();
    }

    public List<Permission.Code> findPermissionsOfUser(User user) {
        String jpql = "SELECT p.code FROM User u "
                    + "LEFT JOIN u.groups g "
                    + "LEFT JOIN g.permissions p WHERE u.id = :id ";
        Query query = em.createQuery(jpql).setParameter("id", user.getId());
        return query.getResultList();
    }
}
